'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const exec = require('child_process').exec;
const q = require('q');

module.exports = class extends Generator {
  prompting() {
    // Have Yeoman greet the user.
    this.log(yosay(
      '欢迎来到mill 的 ' + chalk.red('generator-mill-doc') + ' 文档生成器!'
      ));

    const prompts = [{
      type: 'confirm',
      name: 'someAnswer',
      message: 'Would you like to enable this option?',
      default: true
  }];

  // return this.prompt(prompts).then(props => {
    //   // To access props later use this.props.someAnswer;
    //   this.props = props;
    // });
}

writing() {
    var ye=this;
    // this.fs.copy(
    //   this.templatePath('dummyfile.txt'),
    //   this.destinationPath('dummyfile.txt')
    // );
    
    //var promise=q.nfcall(last.stdout.on,'data');
    this.config.defaults({"filter":["\\s"]})
    //获取文件的基本信息
    let promise2=q.fcall(function () {
        let defer=q.defer();
        var camm=`git log --pretty=format:' {"haxi":"%h","zhush":"%s","zuozhe":"%an","riqi":"%ad"}' -1`;
        var last=exec(camm);
        last.stdout.on('data',function(data){
            defer.resolve(JSON.parse(data))
          // console.log(JSON.parse(data));
      })
        return defer.promise;
        // body...
    });
    //获取最近一次提交的所有文件
    let promise=q.fcall(function(){


        let last=exec(' git log --name-status -1');
        var defer=q.defer();
        last.stdout.on('data',function(data){
            var arr=data.match(/[MAD]\s+.*/g);
            //过滤掉不符合要求的文件名
            let resule=arr.filter(function (item) {
                console.log(item);
              let arr=ye.config.get("filter");
              return arr.every(function (i) {
                     let reg=new RegExp(i);
                     let txt=item.split(/\t/);
                     txt=txt[txt.length-1];
                     let result= reg.test(txt);
                     return !result;
                  });
              });
            ye.log(chalk.blue(resule));
            defer.resolve(resule);
        })
        return defer.promise;
    });
    //等待两个promise都执行完毕
    promise=q.all([promise2,promise]);
    //对文件名进行处理
    promise=promise.then(function(arr){
     
     let resule=  arr[1].map(function(item){
                    let arr=item.split(/\t/);
                    return {
                      type:arr[0],
                      file:arr[1]
                  }
              });
      return {
        files:resule,
        info:arr[0]
      };

    });
    //对文件的变动进行处理
    promise.then(function(glob){
            //处理文件变动
     let proms= glob.files.map(function (item,index) {
        let defer=q.defer();
        let comm=`git log -p ${item.file}`;
        let last= exec(comm);
        last.stdout.on('error',function (error) {
                console.log(chalk.red("文件："+item.file));
                throw error;
        });

        last.stdout.on('data',function (data) {
            let arr=data.split(/commit\s\w*/g);
            var con="";
            if(arr[1])
             con=arr[1].match(/@@[\s\S]*/).toString().replace(/@@.*/,"");
            
            defer.resolve({content:con.toString(),file:item.file});
            // console.log(chalk.red(con.toString()))
            // console.log(chalk.green(index +"--------------\n"));
        })
        return defer.promise;
    });

     //将所有的文件变动打包
    return  q.all(proms).then(function (data) {
 
        return {
            data:data,
            info:glob.info//原有版本信息
        }
        

    });

 }).then(function (data) {

    //写出日志文件
    ye.fs.copyTpl(ye.templatePath('dummyfile.txt')
        , ye.destinationPath(`doc/${data.info.zhush.replace(' ','_').substring(0,10)}.md`),data);
    //写出链接到readme
    ye.fs.append(ye.destinationPath('README.md'), `
### [${data.info.zhush}](doc/${data.info.zhush}.md)
> 说明
        `);
    // ye.fs.
    // console.log(JSON.stringify(data));
 }).catch(function (err) {
  console.error(chalk.red(err));
});

}

install() {
    // this.installDependencies();
}
};
